//
//  ViewController.m
//  iOSLock
//
//  Created by 崔博 on 2018/7/24.
//  Copyright © 2018年 崔博. All rights reserved.
//

#import "ViewController.h"
#import <libkern/OSAtomic.h>
@interface ViewController ()
@property (nonatomic, assign) int ticketsCount;
@property (nonatomic, assign) OSSpinLock lock;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self ticketTest];
    self.lock = OS_SPINLOCK_INIT;
    
}


- (void)saleTicket
{
    

    // 加锁
    OSSpinLockLock(&_lock);
    int oldTicketCount = self.ticketsCount;
    sleep(.2);
    oldTicketCount--;
    self.ticketsCount = oldTicketCount;
    
    NSLog(@"还剩余%d--%@",oldTicketCount,[NSThread currentThread]);
    
    // 解锁
    OSSpinLockUnlock(&_lock);
}

// 卖票演示
- (void)ticketTest
{
    self.ticketsCount = 15;
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        for (int i = 0; i < 5; i++) {
            [self saleTicket];
        }
    });
    dispatch_async(queue, ^{
        for (int i = 0; i < 5; i++) {
            [self saleTicket];
        }
    });
    dispatch_async(queue, ^{
        for (int i = 0; i < 5; i++) {
            [self saleTicket];
        }
    });
}
@end
